<?php
namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AuthCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $next) : Response
    {
        //权限验证
        $controller = $request->controller;
        $action = $request->action;

        //放过验证控制器-方法
        $letgoAry = [
            [
                'controller' => 'app\controller\Index',
                'action' => [
                    'index',
                    'captcha',
                    'login',
                    'logout',
                ]
            ],
            [
                'controller' => 'app\controller\Ajax',
                'action' => [
                    'upField',
                ]
            ],
        ];
        if(!empty($letgoAry)){
            foreach($letgoAry as $k=>$vo){
                if($controller == $vo['controller'] && in_array($action,$vo['action'])){
                    print_r('[放过验证控制器+方法。'.$controller.'-'.$action.']');echo "\n";
                    //放过验证控制器
                    return $next($request);
                }
            }
        }

        //验证session
        $session = $request->session();
        $has = $session->has('token');  //session不存在或者对应的session值为null时返回false，否则返回true。
        if ($has!=true) {
            print_r('session过期');
            //session过期
            return redirect('/');
        }

        if($session->get('roleId')==1){
            print_r('[超级管理 不验证权限。]');echo "\n";
            //超级管理 不验证权限
            return $next($request);
        }

        //验证操作权限
        $role_list = cache('role_list');
        if (!empty($role_list)) {
            $status = false;

            foreach($role_list as $key=>$val){
                if($session->get('roleId')==$val['id']){
                    $basePurview = explode(',',$val['base_purview']);

                    $controllerAry = explode('controller',strtolower($controller));
                    $cf = substr($controllerAry[1],1) . '_' . $action;

                    if (in_array($cf,$basePurview)){
                        $status = true;
                        break;
                    }
                }
            }
            if($status == false){
                print_r('[暂无权限。'.$controller.'-'.$action.']');echo "\n";
                return return_json(0,'暂无权限');
            }
        }

        return $next($request);
    }
}
